package logic

import (
	"context"
	"fmt"
	"user/modles"
	"user/pkg"

	"user/user_rpc/internal/svc"
	"user/user_rpc/user_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *user_rpc.UserRegisterRequest) (*user_rpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	User := modles.User{
		UserName:     in.UserName,
		UserAccount:  in.UserAccount,
		UserPassword: pkg.Md5(in.UserPassword),
		UserMobile:   in.UserMobile,
	}
	json_code, _ := modles.Rdb.Get(modles.Ctx, fmt.Sprintf("SmsCaptcha_UserMobile:%s", in.UserMobile)).Result()
	if json_code != in.SmsCode {
		return &user_rpc.UserRegisterResponse{}, fmt.Errorf("验证码错误")
	}
	if modles.DB.Where("user_account = ?", User.UserAccount).Limit(1).Find(&User).Error != nil {
		return &user_rpc.UserRegisterResponse{}, fmt.Errorf("服务器繁忙")
	}
	if User.ID != 0 {
		return &user_rpc.UserRegisterResponse{}, fmt.Errorf("账号已存在")
	}
	if modles.DB.Create(&User).Error != nil {
		return &user_rpc.UserRegisterResponse{}, fmt.Errorf("服务器繁忙")
	}
	if modles.DB.Where("user_account = ?", User.UserAccount).Limit(1).Find(&User).Error != nil {
		return &user_rpc.UserRegisterResponse{}, fmt.Errorf("服务器繁忙")
	}
	return &user_rpc.UserRegisterResponse{
		UserId: int64(User.ID),
	}, nil
}
